/*
 * Copyright (C) 2012  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.util.log.output;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * CustomizedFormatter : The customized JUL formatter.
 * 
 * @author Romain DUBOIS
 */
public class CustomizedFormatter extends Formatter {

    /** The format to use */
    private final String mFormat;

    /**
     * Constructor
     * 
     * @param pFormat
     *            The format to use
     */
    public CustomizedFormatter(final String pFormat) {
        super();
        mFormat = pFormat;
    }

    /**
     * {@inheritDoc}
     * 
     * @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
     */
    @Override
    public String format(final LogRecord pRecord) {
        final StringWriter lWriter = new StringWriter();
        final PrintWriter lPrinter = new PrintWriter(lWriter);

        // Main line
        final Date lDate = new Date(pRecord.getMillis());
        // final StringBuilder lBuilder = new StringBuilder();
        lPrinter.append(String.format(mFormat, pRecord.getLevel().getLocalizedName(),
                pRecord.getLoggerName(), lDate, Long.valueOf(pRecord.getMillis()),
                pRecord.getSourceClassName(), pRecord.getSourceMethodName(), pRecord.getMessage()));
        lPrinter.println();

        // Exception (if any)
        if (pRecord.getThrown() != null) {
            pRecord.getThrown().printStackTrace(lPrinter);
        }
        lPrinter.close();

        return lWriter.toString();
    }
}
